﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using ZG_member.BLL;
using System.Configuration;
using System.Threading;

namespace ZG_member
{
    public partial class RechargeMoneyChart : Form
    {
        public RechargeMoneyChart()
        {
            InitializeComponent();
            skinEngine1.SkinFile = Application.StartupPath + ConfigurationManager.AppSettings["Skin"];
            this.Opacity = 0;
            jiazai();
        }

        //*********************折线图***************************
        private Thread addDataRunner;
        private Random rand = new Random();
        public delegate void AddDataDelegate();
        public AddDataDelegate addDataDel;
        DataTable dt1=null;
        DataTable dt2=null;
        DataTable dt3=null;
        private void AddDataThreadLoop()
        {
            while (true)
            {
                chart2.Invoke(addDataDel);

                Thread.Sleep(110);
                if (num == 12)
                {
                    addDataRunner.Suspend();
                    break;
                }
            }
        }
        
        int num = 0;
        public void AddData()
        {
            num++;
            int listCount = listBox1.Items.Count;
            wasteBook waste = new wasteBook();
            //int xuanzeriqi =Convert.ToInt32( dtpStart.Text);
            for (int i = 0; i < listCount; i++)
            {
                if(i==0)
                {
                        foreach (Series ptSeries in chart2.Series)
                        {

                            AddNewPoint(num, ptSeries, dt1,i);
                        }
                }
                if (i == 1)
                {
                    foreach (Series ptSeries in chart2.Series)
                    {

                        AddNewPoint(num, ptSeries, dt2,i);
                    }
                }
                if (i == 2)
                {
                    foreach (Series ptSeries in chart2.Series)
                    {

                        AddNewPoint(num, ptSeries, dt3,i);
                    }
                }
            }
            //this.timer3.Stop();
        }

        /// The AddNewPoint function is called for each series in the chart when
        /// new points need to be added.  The new point will be placed at specified
        /// X axis (Date/Time) position with a Y value in a range +/- 1 from the previous
        /// data point's Y value, and not smaller than zero.

        public void AddNewPoint(int timeStamp, System.Windows.Forms.DataVisualization.Charting.Series ptSeries,DataTable dt,int vv)
        {
            double newVal = 0;

            //if (ptSeries.Points.Count > 0)
            //{
            //    newVal = ptSeries.Points[ptSeries.Points.Count - 1].YValues[0] + ((rand.NextDouble() * 2) - 1);
            //}

            if (newVal < 0)
                newVal = 0;
            int sa = listBox1.Items.Count;
            // Add new data point to its series.
       
              
                if (ptSeries.Name == listBox1.Items[vv].ToString() + " - 消费金额")
                {
                    bool st = true;
                    if (dt.Rows.Count == 0)
                    {
                        st = false;
                    }
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (timeStamp == Convert.ToInt32(dt.Rows[i]["月"]))
                        {
                            ptSeries.Points.AddXY(timeStamp, Convert.ToInt32(dt.Rows[i]["消费金额"]));
                            st = true;
                            break;
                        }
                        else
                        {
                            //ptSeries.Points.AddXY(timeStamp, 0);
                            //break;                    
                            st = false;
                        }
                    }

                    if (st == false)
                    {
                        ptSeries.Points.AddXY(timeStamp, 0);
                    }
                 
                }
                if (ptSeries.Name == listBox1.Items[vv].ToString() + " - 充值金额")
                {
                    bool stt = true;
                    if (dt.Rows.Count == 0)
                    {
                        stt = false;
                    }
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (timeStamp == Convert.ToInt32(dt.Rows[i]["月"]))
                        {
                            ptSeries.Points.AddXY(timeStamp, Convert.ToInt32(dt.Rows[i]["充值金额"]));
                            stt = true;
                            break;
                        }
                        else
                        {
                            //ptSeries.Points.AddXY(timeStamp, 0);
                            //break;                    
                            stt = false;
                        }
                    }

                    if (stt == false)
                    {
                        ptSeries.Points.AddXY(timeStamp, 0);
                    }
                }
              
            
            
            // remove all points from the source series older than 1.5 minutes.

            //double removeBefore = timeStamp.AddSeconds((double)(6) * (-1)).ToOADate();
            ////remove oldest values to maintain a constant number of data points
            //while (ptSeries.Points[0].XValue < removeBefore)
            //{

            //    ptSeries.Points.RemoveAt(0);
            //}

            chart2.ChartAreas[0].AxisX.Minimum = 1;
            chart2.ChartAreas[0].AxisX.Maximum = 12;


            chart2.Invalidate();
        }

        /// Clean up any resources being used.
        protected override void Dispose(bool disposing)
        {
            if ((addDataRunner.ThreadState & ThreadState.Suspended) == ThreadState.Suspended)
            {
                addDataRunner.Resume();
            }
            addDataRunner.Abort();

            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }



        //******************************************************



        public void ExportExcel(string fileName, DataGridView myDGV)
        {

            string saveFileName = "";
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Filter = "*.xlsx|*.xlsx|*.xls|*.xls";
            saveDialog.FilterIndex = 2;
            saveDialog.FileName = fileName + "Excel导出";
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;

            if (saveFileName.IndexOf(":") < 0)
            {
                return;
            }//被点了取消 
            else
            {
                //MessageBoxTimeout.Show("正在导出···，请稍等！", "系统提示", 2000);
            }
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象，可能您的机子未安装Office.Excel组件");
                return;
            }
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 
            //写入标题
            for (int i = 0; i < myDGV.ColumnCount; i++)
            {
                worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
            }
            //写入数值
            for (int r = 0; r < myDGV.Rows.Count; r++)
            {
                for (int i = 0; i < myDGV.ColumnCount; i++)
                {
                    worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
                }
                System.Windows.Forms.Application.DoEvents();
            }
            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应

            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);
                }
                catch (Exception ex)
                {
                    //fileSaved = false;
                    MessageBox.Show("导出文件时出错,文件可能正被打开！\n" + ex.Message);
                }
            }
            xlApp.Quit();
            GC.Collect();//强行销毁 
            MessageBox.Show(saveFileName + "的资料保存成功", "提示", MessageBoxButtons.OK);
        }
        public void sousuo() {
            num = 0;
            memberInfo memInfo = new memberInfo();
            string unit = "";
            DataTable dt;
            chart2.Series.Clear();
            if (label1.Text == "选择日期")
            {
                if (0 == 0)
                {
                    flagTab = 1;
                    //*********************以下是折现图************************
                    chart2.Series.Clear();
                    wasteBook waste=new wasteBook();
                    for (int i = 0; i < listBox1.Items.Count; i++)
		        	{
			            if(i==0)
                        {
                           dt1 = waste.GetSQL("select datepart(month,date) as 月, SUM(consumeMoney) as 消费金额,SUM(savingMoney) as 充值金额  from wasteBook  where date>'" + (Convert.ToInt32(this.listBox1.Items[i])).ToString() + "' and date<'" + (Convert.ToInt32(this.listBox1.Items[i]) + 1).ToString() + "' group by datepart(month,date)").Tables[0];
                        }
                        if(i==1)
                        {
                          dt2=waste.GetSQL("select datepart(month,date) as 月, SUM(consumeMoney) as 消费金额,SUM(savingMoney) as 充值金额  from wasteBook  where date>'" + (Convert.ToInt32(this.listBox1.Items[i])).ToString() + "' and date<'" + (Convert.ToInt32(this.listBox1.Items[i]) + 1).ToString() + "' group by datepart(month,date)").Tables[0];
                        }
                        if(i==2)
                        {
                          dt3=waste.GetSQL("select datepart(month,date) as 月, SUM(consumeMoney) as 消费金额,SUM(savingMoney) as 充值金额  from wasteBook  where date>'" + (Convert.ToInt32(this.listBox1.Items[i])).ToString() + "' and date<'" + (Convert.ToInt32(this.listBox1.Items[i]) + 1).ToString() + "' group by datepart(month,date)").Tables[0];
                        }
			        }


                    // create a line chart series
                    if (this.checkBox1.Checked)
                    {
                        for (int i = 0; i < listBox1.Items.Count; i++)
                        {
                            List<Color> list = new List<Color>() {Color.Red,Color.RosyBrown,Color.Salmon };
                            Series newSeries = new Series(listBox1.Items[i].ToString()+" - 充值金额");
                            newSeries.ChartType = SeriesChartType.Line;
                            newSeries.BorderWidth = 2;
                            newSeries.Color = list[i];
                            //newSeries.XValueType = ChartValueType.DateTime;
                            chart2.Series.Add(newSeries);
                        }
                      
                    }
                    if (this.checkBox2.Checked)
                    {
                        for (int i = 0; i < listBox1.Items.Count; i++)
                        {
                            List<Color> list = new List<Color>() { Color.SandyBrown, Color.SeaGreen, Color.SeaShell };
                            Series newSeries2 = new Series(listBox1.Items[i].ToString() + " - 消费金额");
                            newSeries2.ChartType = SeriesChartType.Line;
                            newSeries2.BorderWidth = 2;
                            newSeries2.Color = list[i];
                            //newSeries.XValueType = ChartValueType.DateTime;
                            chart2.Series.Add(newSeries2);
                            // start worker threads.
                        }       
                    }
                    Application.DoEvents();
                    this.timer3.Start();

                    //if (addDataRunner.IsAlive == true)
                    //{
                    //    addDataRunner.Resume();
                    //}
                    //else
                    //{
                    //    //if (chart2.Series.Count<0)
                    //    //{
                    //    //    addDataRunner.Suspend();
                    //    //}
                    //    addDataRunner.Start();
                    //}

                    //addDataRunner.Abort();
                    return;
                }
            }
            switch (cbxDateUnit.Text)
            {

                case "月":
                    unit = "MM";
                    dt = memInfo.GetListSql("select  convert(varchar,DATEPART (YYYY , date ))+ '年' + convert(varchar,DATEPART (MM , date )) + '月' as dateU,sum(consumeMoney) as 消费,sum(savingMoney) as 储值 from wasteBook where date>='" + dtpStart.Value + "' and date<='" + dtpEnd.Value + "' group by DATEPART (YYYY , date ),DATEPART (MM , date ) order by DATEPART (YYYY , date ),DATEPART (MM , date )").Tables[0];

                    break;
                case "季度":
                    unit = "Q";
                    dt = memInfo.GetListSql("select  convert(varchar,DATEPART (YYYY , date ))+ '年' + convert(varchar,DATEPART (Q , date )) + '季度' as dateU,sum(consumeMoney) as 消费,sum(savingMoney) as 储值 from wasteBook where date>='" + dtpStart.Value + "' and date<='" + dtpEnd.Value + "' group by DATEPART (YYYY , date ),DATEPART (Q , date ) order by DATEPART (YYYY , date ),DATEPART (Q , date )").Tables[0];

                    break;
                case "年":
                    unit = "YYYY";
                    dt = memInfo.GetListSql("select  DATEPART (YYYY , date ) dateU,sum(consumeMoney) as 消费,sum(savingMoney) as 储值 from wasteBook where date>='" + dtpStart.Value + "' and date<='" + dtpEnd.Value + "' group by DATEPART (YYYY , date )").Tables[0];

                    break;
                default:
                    unit = "DD";
                    dt = memInfo.GetListSql("select  convert(varchar,date ) dateU,sum(consumeMoney) as 消费,sum(savingMoney) as 储值 from wasteBook where date>='" + dtpStart.Value + "' and date<='" + dtpEnd.Value + "' group by date").Tables[0];
                    break;
            }




            //DataTable dt = memInfo.GetListSql("select convert(varchar,DATEPART (YYYY , date ))+ '年' + convert(varchar,DATEPART (MM , date )) as dateU,sum(consumeMoney) as 消费,sum(savingMoney) as 储值 from wasteBook where date>='" + dtpStart.Value + "' and date<='" + dtpEnd.Value + "' group by DATEPART (YYYY , date ),DATEPART (" + unit + " , date ) order by DATEPART (YYYY , date ),DATEPART (" + unit + " , date )").Tables[0];

            chart1.DataSource = null;

            chart1.DataSource = dt;
            chart1.Series["充值总额"].XValueMember = "dateU";
            chart1.Series["充值总额"].YValueMembers = "储值";
            chart1.Series["消费总额"].XValueMember = "dateU";
            chart1.Series["消费总额"].YValueMembers = "消费";
            chart1.DataBind();

            chart1.ChartAreas["ChartArea1"].AxisX.Title = cbxDateUnit.Text;

            dgvDate.DataSource = dt;
            if (dt.Rows.Count > 9) //当X轴超过9时就会显示不完全
            {
                //设置X轴坐标的间隔为1
                chart1.ChartAreas["ChartArea1"].AxisX.Interval = 1;
                //设置X轴坐标的偏移为1
                chart1.ChartAreas["ChartArea1"].AxisX.IntervalOffset = 1;
                //设置交错显示，例如数据多时可分两行显示
                chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.IsStaggered = true;
            }
        }

        private void btnsubmit_Click(object sender, EventArgs e)
        {
            //num = 0;
            //memberInfo memInfo = new memberInfo();
            //string unit = "";
            //DataTable dt;
            //chart2.Series.Clear();
            //if (label1.Text == "选择日期")
            //{
            //    if (0 == 0)
            //    {
            //        flagTab = 1;
            //        //*********************以下是折现图************************
            //        chart2.Series.Clear();
            //        // create a line chart series
            //        Series newSeries = new Series("充值金额");
            //        newSeries.ChartType = SeriesChartType.Line;
            //        newSeries.BorderWidth = 2;
            //        newSeries.Color = Color.OrangeRed;
            //        //newSeries.XValueType = ChartValueType.DateTime;
            //        chart2.Series.Add(newSeries);
            //        Series newSeries2 = new Series("消费金额");
            //        newSeries2.ChartType = SeriesChartType.Line;
            //        newSeries2.BorderWidth = 2;
            //        newSeries2.Color = Color.Blue;
            //        //newSeries.XValueType = ChartValueType.DateTime;
            //        chart2.Series.Add(newSeries2);
            //        // start worker threads.
                   
            //            Application.DoEvents();
            //            this.timer3.Start();
                    
            //        //if (addDataRunner.IsAlive == true)
            //        //{
            //        //    addDataRunner.Resume();
            //        //}
            //        //else
            //        //{
            //        //    //if (chart2.Series.Count<0)
            //        //    //{
            //        //    //    addDataRunner.Suspend();
            //        //    //}
            //        //    addDataRunner.Start();
            //        //}

            //        //addDataRunner.Abort();
            //        return;
            //    }
            //}
            //switch (cbxDateUnit.Text)
            //{ 

            //    case "月":
            //        unit = "MM";
            //        dt = memInfo.GetListSql("select  convert(varchar,DATEPART (YYYY , date ))+ '年' + convert(varchar,DATEPART (MM , date )) + '月' as dateU,sum(consumeMoney) as 消费,sum(savingMoney) as 储值 from wasteBook where date>='" + dtpStart.Value + "' and date<='" + dtpEnd.Value + "' group by DATEPART (YYYY , date ),DATEPART (MM , date ) order by DATEPART (YYYY , date ),DATEPART (MM , date )").Tables[0];

            //        break;
            //    case "季度":
            //        unit = "Q";
            //        dt = memInfo.GetListSql("select  convert(varchar,DATEPART (YYYY , date ))+ '年' + convert(varchar,DATEPART (Q , date )) + '季度' as dateU,sum(consumeMoney) as 消费,sum(savingMoney) as 储值 from wasteBook where date>='" + dtpStart.Value + "' and date<='" + dtpEnd.Value + "' group by DATEPART (YYYY , date ),DATEPART (Q , date ) order by DATEPART (YYYY , date ),DATEPART (Q , date )").Tables[0];

            //        break;
            //    case "年":
            //        unit = "YYYY";
            //        dt = memInfo.GetListSql("select  DATEPART (YYYY , date ) dateU,sum(consumeMoney) as 消费,sum(savingMoney) as 储值 from wasteBook where date>='" + dtpStart.Value + "' and date<='" + dtpEnd.Value + "' group by DATEPART (YYYY , date )").Tables[0];

            //        break;
            //    default:
            //        unit = "DD";
            //        dt = memInfo.GetListSql("select  convert(varchar,date ) dateU,sum(consumeMoney) as 消费,sum(savingMoney) as 储值 from wasteBook where date>='" + dtpStart.Value + "' and date<='" + dtpEnd.Value + "' group by date").Tables[0];
            //        break;
            //}



            
            ////DataTable dt = memInfo.GetListSql("select convert(varchar,DATEPART (YYYY , date ))+ '年' + convert(varchar,DATEPART (MM , date )) as dateU,sum(consumeMoney) as 消费,sum(savingMoney) as 储值 from wasteBook where date>='" + dtpStart.Value + "' and date<='" + dtpEnd.Value + "' group by DATEPART (YYYY , date ),DATEPART (" + unit + " , date ) order by DATEPART (YYYY , date ),DATEPART (" + unit + " , date )").Tables[0];

            //chart1.DataSource = null;

            //chart1.DataSource = dt;
            //chart1.Series["充值总额"].XValueMember = "dateU";
            //chart1.Series["充值总额"].YValueMembers = "储值";
            //chart1.Series["消费总额"].XValueMember = "dateU";
            //chart1.Series["消费总额"].YValueMembers = "消费";
            //chart1.DataBind();

            //chart1.ChartAreas["ChartArea1"].AxisX.Title = cbxDateUnit.Text;

            //dgvDate.DataSource = dt;
            //if (dt.Rows.Count > 9) //当X轴超过9时就会显示不完全
            //{
            //    //设置X轴坐标的间隔为1
            //    chart1.ChartAreas["ChartArea1"].AxisX.Interval = 1;
            //    //设置X轴坐标的偏移为1
            //    chart1.ChartAreas["ChartArea1"].AxisX.IntervalOffset = 1;
            //    //设置交错显示，例如数据多时可分两行显示
            //    chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.IsStaggered = true;
            //}
            sousuo();
        }
        private void RechargeMoneyChart_Load(object sender, EventArgs e)
        {
            this.button1.Visible = false;
            this.listBox1.Visible = false;
            this.button2.Visible = false;
            this.checkBox1.Visible = false;
            this.checkBox2.Visible = false;
        }
        public void jiazai() {
            ThreadStart addDataThreadStart = new ThreadStart(AddDataThreadLoop);
            // create the Adding Data Thread but do not start until start button clicked

            addDataRunner = new Thread(addDataThreadStart);

            // create a delegate for adding data
            addDataDel += new AddDataDelegate(AddData);
            this.timer1.Start();
            cbxDateUnit.Text = "月";

            dtpStart.Value = dtpStart.Value.AddMonths(-1);
            Series s1 = new Series("充值总额");
            chart1.Series.Add(s1);
            Series s2 = new Series("消费总额");
            chart1.Series.Add(s2);
            chart1.Series["充值总额"].IsValueShownAsLabel = true;
            chart1.Series["消费总额"].IsValueShownAsLabel = true;
        
        }
        private void btnExport_Click(object sender, EventArgs e)
        {
            ExportExcel(" ", dgvDate);

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            this.Left += 2;
            this.Opacity += 0.1;
            if (Opacity == 1)
            {
                this.timer1.Stop();

            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            this.Top = this.Top + 10;
            this.Opacity = this.Opacity - 0.06;
            if (Opacity <= 0)
            {
                this.timer2.Stop();
                this.Close();
            }
        }
        int flag = 0;
        private void RechargeMoneyChart_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (flag == 0)
            {
                e.Cancel = true;
                flag = 1;
                this.timer2.Start();
            }
        }

        private void tabControl1_Deselected(object sender, TabControlEventArgs e)
        {
            
            
        }

        int flagTab = 0;
        private void tabControl1_Click(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedIndex == 2)
            {
                dtpEnd.Visible = false;
                cbxDateUnit.Enabled = false;
                label1.Text = "选择日期";
                dtpStart.CustomFormat = "yyyy";
                dtpStart.Format = DateTimePickerFormat.Custom;
                dtpStart.ShowUpDown = true;
                btnExport.Visible = false;
                this.label2.Visible = false;
                this.label3.Visible = false;
                this.cbxDateUnit.Visible = false;
                this.listBox1.Visible = true;
                this.button1.Visible = true;
                this.button2.Visible = true;
                this.checkBox1.Visible = true;
                this.checkBox2.Visible = true;
            }
            if(this.tabControl1.SelectedIndex==0||this.tabControl1.SelectedIndex==1)
            {
                dtpEnd.Visible = true;
                cbxDateUnit.Enabled = true;
                label1.Text = "起始时间";
                dtpStart.CustomFormat = "";
                dtpStart.Format = DateTimePickerFormat.Long;
                dtpStart.ShowUpDown = false;
                btnExport.Visible = true;
                this.label2.Visible = true;
                this.label3.Visible = true;
                this.cbxDateUnit.Visible = true;
                this.listBox1.Visible = false;
                this.button1.Visible=false;
                this.button2.Visible = false;
                this.checkBox1.Visible = false;
                this.checkBox2.Visible = false;
            }

        }

        private void timer3_Tick(object sender, EventArgs e)
        {
            

                AddData();
                Application.DoEvents();
               if (num ==12)
	            {
		             this.timer3.Stop();
	            }
            
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if(!this.listBox1.Items.Contains(this.dtpStart.Text)&&this.listBox1.Items.Count<3)
            {
                this.listBox1.Items.Add(this.dtpStart.Text);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.listBox1.Items.RemoveAt(this.listBox1.SelectedIndex);
        }

        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            this.listBox1.Items.RemoveAt(this.listBox1.SelectedIndex);
        }

    



    }
}
